import axios from "axios";
import { ElMessage } from 'element-plus';
import Config from "@/config/env";
import _ from "lodash";
import i18n from "@/i18n";

// 替换为简单的全局数组
let pendingRequests = [];

const codeMessage = {
  200: "服务器成功返回请求的数据。",
  201: "新建或修改数据成功。",
  202: "一个请求已经进入后台排队（异步任务）。",
  204: "删除数据成功。",
  400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户验证失败，请重新登录",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "服务器发生错误，请检查服务器。",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。",
};
axios.defaults.baseURL = Config.baseUrl;

const langMap = {
  ZhCN: 'zh-CN',
  EnUS: 'en-US',
  Kz: 'kk-KZ',
  RuRU: 'ru-RU',
}
// create an axios instance
const service = (params, isFilePost) => {
  const serviceFetch = axios.create({
    timeout: 120000, 
  });
  // request interceptor

  serviceFetch.interceptors.request.use(
    (config) => {
      let postKey = "";
      if (config.method === "post" || config.method === "delete" || config.method === "put" || config.method === "patch") {
        postKey = "data";
      } else {
        postKey = "params";
      }
      config[postKey] = config[postKey] || {};
      const token = Storage.get("token", true) || "";
      if (token) {
        config.headers = {
          Authorization: 'Bearer ' + token,
          ...config.headers,
        };
      }
      // 从i18n实例中获取当前语言
      const currentLanguage = i18n.global.locale.value;
      
      // 设置Accept-Language头
      config.headers['Accept-Language'] = langMap[currentLanguage];
      // 把进行请求cancel方法，存入全局数组，在页面切换时调用 cancel， cancel 还未结束的请求
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      config.cancelToken = source.token;
      
      // 如果参数中 指明 不要 cancel，则不存入全局数组
      if (!config[postKey].forbidCancel) {
        pendingRequests.push(source.cancel);
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // respone interceptor
  serviceFetch.interceptors.response.use(
    (response) => {
      if (response.data.status && response.data.status != 200) {
        ElMessage.closeAll();
        ElMessage.error(response.data.message || "服务异常");
        if (response.status === 401 || response.data.status == 20005 || response.data.status == 20006) {
          setTimeout(() => {
            window.location.href = `${location.origin}${location.pathname}#/login`;
          }, 200);
        }
      }
      if (isFilePost) {
        const { responseType } = response.request
        if (responseType === 'blob' && response.data.type.includes('application/json')) {
          response.data.isJson = true
        } if (responseType === 'blob' && !response.data.type.includes('application/json')) {
          let filename = response.headers['content-disposition'].split(';').find(v => v.includes('filename')).split('filename=')[1]
          return { filename: decodeURIComponent(filename), file: response.data }
        }
      }
      return response.data;
    },
    (error) => {
      let rep = error.response;
      if (rep) {
        // 对状态码非200 做判断；
        if (rep.status !== 200) {
          ElMessage.error(rep.data.message || i18n.global.t('login.' + codeMessage[rep.status]));
          // 用户认真失败-重新登录
          if (rep.status === 401 || response.data.status == 20005 || response.data.status == 20006) {
            setTimeout(() => {
              window.location.href = `${location.origin}${location.pathname}#/login`;
            }, 200);
          }
        }
      }
      return Promise.reject(error.response?.data);
    }
  );
  return serviceFetch(params);
};

// 添加清除所有pending请求的方法
service.cancelAll = () => {
  pendingRequests.forEach(cancel => {
    typeof cancel === 'function' && cancel('Navigation canceled');
  });
  pendingRequests = [];
};

service.all = axios.all;
export default service;
